<template>
  <el-dialog v-model="visible" title="购买护理项目" width="90%">
    <!-- 顶部信息展示 -->
    <div class="info-text">
      客户姓名：{{ clientName }}　|　护理级别：{{ levelName }}
    </div>

    <!-- 可购买项目 -->
    <h3 class="subtitle">可购买护理项目</h3>
    <el-input v-model.trim="searchName" placeholder="输入护理项目名称查询" style="width: 300px; margin-bottom: 10px" clearable
      @clear="handleSearch" @keyup.enter="handleSearch" />
    <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
    <el-table :data="tableData" border style="width: 100%; background: #f5f7fa;"
      :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="projectId" label="编号" width="100" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="cycle" label="执行周期" />
      <el-table-column prop="frequency" label="执行次数" />
      <el-table-column label="服务购买时间">
        <template #default="scope">
          {{ scope.row.startDate }}
        </template>
      </el-table-column>
      <el-table-column label="购买数量">
        <template #default="scope">
          <el-input-number v-model="scope.row.quantity" :min="1" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column label="购买时长（月）">
        <template #default="scope">
          <el-select v-model="scope.row.months" placeholder="请选择" style="width: 100%">
            <el-option v-for="m in 6" :key="m" :label="`${m}个月`" :value="m" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="服务到期时间">
        <template #default="scope">
          {{ calculateEndDate(scope.row.startDate, scope.row.months) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button type="primary" size="small" @click="purchaseSingle(scope.row)">购买</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-bar">
      <el-pagination v-model:current-page="pagination.cur" v-model:page-size="pagination.size" :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper" :page-sizes="[2, 5, 10]" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 已购买项目 -->
    <h3 class="subtitle">已购买护理项目</h3>
    <el-table :data="boughtList" border style="width: 100%; background: #f5f7fa;"
      :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }">
      <el-table-column prop="nursingProject.projectId" label="ID" width="80" />
      <el-table-column prop="nursingProject.name" label="名称" />
      <el-table-column prop="nursingProject.price" label="价格" />
      <el-table-column prop="nursingProject.frequency" label="执行次数" />
      <el-table-column prop="nursingProject.cycle" label="执行周期" />
      <el-table-column prop="nursingProject.description" label="描述" />
      <el-table-column prop="clientNursingProject.startDate" label="服务开始时间" />
      <el-table-column prop="clientNursingProject.endDate" label="服务到期时间" />
      <el-table-column prop="clientNursingProject.quantity" label="购买数量" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button type="danger" size="small" @click="removePurchasedProject(scope.row.clientNursingProject)">
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-bar">
      <el-pagination v-model:current-page="boughtPagination.cur" v-model:page-size="boughtPagination.size"
        :total="boughtPagination.total" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[2, 5, 10]"
        @size-change="handleBoughtSizeChange" @current-change="handleBoughtCurrentChange" />
    </div>

    <!-- 操作按钮 -->
    <div style="text-align: center; margin-top: 20px">
      <el-button type="primary" @click="handleConfirm">确认</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose } from 'vue'
import { inject } from 'vue'
const axios = inject("axios")
import qs from 'qs'
import { ElMessage } from 'element-plus'

const visible = ref(false)
const clientName = ref('')
const clientId = ref(null)
const levelId = ref(null)
const levelName = ref('')
const tableData = ref([])
const boughtList = ref([])
const searchName = ref('')

const pagination = ref({ cur: 1, size: 5, total: 0 })
const boughtPagination = ref({ cur: 1, size: 5, total: 0 })
const fullDataMap = new Map()

const open = async (incomingClientId, incomingClientName, incomingLevelId, incomingLevelName) => {
  visible.value = true
  clientId.value = incomingClientId
  clientName.value = incomingClientName
  levelId.value = incomingLevelId
  levelName.value = incomingLevelName

  pagination.value.cur = 1
  boughtPagination.value.cur = 1
  fullDataMap.clear()
  tableData.value = []
  boughtList.value = []

  await fetchUnboughtProjects()
  await fetchBoughtProjects()
}

const fetchUnboughtProjects = async () => {
  const res = await axios.get('/clientNursingProject/pageNursingProject', {
    params: {
      projectName: searchName.value,
      cur: pagination.value.cur,
      number: pagination.value.size,
      name: clientName.value,
      levelId: levelId.value
    }
  })
  if (res.data.status === 200) {
    const current = res.data.data.map(p => {
      const cached = fullDataMap.get(p.projectId)
      return {
        ...p,
        startDate: cached?.startDate || formatDate(new Date()),
        quantity: cached?.quantity || 1,
        months: cached?.months || 3 // 默认购买3个月
      }
    })
    tableData.value = current
    current.forEach(p => fullDataMap.set(p.projectId, p))
    pagination.value.total = res.data.total
  }
}

const handleSearch = () => {
  pagination.value.cur = 1
  fetchUnboughtProjects()
}


const fetchBoughtProjects = async () => {
  const res = await axios.get('/clientNursingProject/pageClientAndProjectByName', {
    params: {
      cur: boughtPagination.value.cur,
      number: boughtPagination.value.size,
      name: clientName.value
    }
  })
  if (res.data.status === 200) {
    boughtList.value = res.data.data || []
    boughtPagination.value.total = res.data.total
  }
}

const handleConfirm = () => {
  visible.value = false
  fullDataMap.clear()
}

const handleSizeChange = (s) => {
  pagination.value.size = s
  pagination.value.cur = 1
  fetchUnboughtProjects()
}
const handleCurrentChange = (p) => {
  pagination.value.cur = p
  fetchUnboughtProjects()
}

const handleBoughtSizeChange = (s) => {
  boughtPagination.value.size = s
  boughtPagination.value.cur = 1
  fetchBoughtProjects()
}
const handleBoughtCurrentChange = (p) => {
  boughtPagination.value.cur = p
  fetchBoughtProjects()
}
const calculateEndDate = (startDate, months) => {
  if (!startDate || !months) return ''
  const s = new Date(startDate)
  s.setMonth(s.getMonth() + months) // 使用选择的月数
  return formatDate(s)
}


const formatDate = (d) => {
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

const purchaseSingle = async (row) => {
  if (!row.startDate || !row.months || !row.quantity) {
    ElMessage.warning('请填写完整的服务购买时间、时长与数量')
    return
  }

  const start = new Date(row.startDate)
  const end = new Date(start)
  end.setMonth(start.getMonth() + row.months)

  const params = {
    clientId: clientId.value,
    projectId: row.projectId,
    levelId: levelId.value,
    startDate: formatDate(start),
    endDate: formatDate(end),
    quantity: row.quantity
  }

  try {
    const res = await axios.post(
      '/clientNursingProject/addClientNursingProject',
      qs.stringify(params),
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    )
    if (res.data.status !== 200) throw new Error(res.data.msg)
    ElMessage.success('添加成功')
    fetchUnboughtProjects()
    fetchBoughtProjects()
  } catch (err) {
    ElMessage.error(`添加失败：${err.message}`)
  }
}


const removePurchasedProject = async (project) => {
  try {
    const res = await axios.post(
      '/clientNursingProject/deleteClientNursingProjectById',
      qs.stringify({
        clientId: clientId.value,
        projectId: project.projectId,
        levelId: levelId.value
      }),
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    )
    if (res.data.status === 200) {
      ElMessage.success('移除成功')
      fullDataMap.delete(project.projectId)  // ✅ 清除缓存，避免保留购买时间和数量
      fetchUnboughtProjects()
      fetchBoughtProjects()
    } else {
      throw new Error(res.data.msg)
    }
  } catch (err) {
    ElMessage.error('移除失败：' + err.message)
  }
}


defineExpose({ open })
</script>

<style scoped>
.subtitle {
  font-size: 18px;
  font-weight: 500;
  margin: 20px 0 10px 0;
  color: #333;
}

.info-text {
  margin-bottom: 20px;
  font-weight: bold;
  color: #333;
}

.pagination-bar {
  display: flex;
  justify-content: flex-end;
  margin-top: 2%;
  margin-bottom: 2%;
}
</style>
